//
//  Ext+Image.swift
//  Waterfall
//
//  Created by jh on 2023/6/9.
//

import UIKit

extension UIImage {
    static func systemImage(name: String, weight: SymbolWeight) -> UIImage? {
        let config = UIImage.SymbolConfiguration(weight: weight)
        return UIImage(systemName: name, withConfiguration: config)
    }
    
    static func imageWithCapture(view: UIView, rect: CGRect) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
        if let ctx = UIGraphicsGetCurrentContext() {
            view.layer.render(in: ctx)
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            let newRect = CGRect(x: 0,y: 0, width: rect.size.width * UIScreen.main.scale, height: rect.size.height * UIScreen.main.scale)
            // 需要乘以屏幕分辨率
            if let imagRef = newImage?.cgImage?.cropping(to: newRect) {
                let nImage = UIImage(cgImage: imagRef)
                UIGraphicsEndImageContext()
                return nImage;
            } else {
                UIGraphicsEndImageContext()
                return nil
            }
        } else {
            UIGraphicsEndImageContext()
            return nil
        }
    }
    
    var floatSize: CGSize {
        let rate = self.size.width / self.size.height
        if rate > 1 {
            return CGSize(width: 200, height: 200 / rate)
        } else {
            return CGSize(width: 200 * rate, height: 200)
        }
    }
}
